package main.二叉树;

import common.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author tmh
 * @date 2024/7/22 13:55
 * @description
 */
public class T102二叉树的层序遍历 {
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        if (root == null) {
            return result;
        }
        //如果要用队列的性质的话，那么就用offer方法把节点加入到deque里面
        deque.offer(root);
        while (!deque.isEmpty()) {
            int len = deque.size();
            List<Integer> list = new ArrayList<>();
            while (len > 0) {
                TreeNode temp = deque.poll();
                list.add(temp.val);
                if (temp.left != null) {
                    deque.offer(temp.left);
                }
                if (temp.right != null) {
                    deque.offer(temp.right);
                }
                len--;
            }
            result.add(list);
        }
        return result;
    }
}
